package com.example.demo2.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo2.entity.Comment;
import com.example.demo2.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService extends ServiceImpl<CommentMapper, Comment> {
    @Autowired
    private CommentMapper commentMapper;

    public List<Comment> getALlByForeignId(Integer foreignId) {
        return commentMapper.findAllInfoByForeignId(foreignId);
    }

    public Map<String, Object> getALlByForeignId2(Integer foreignId) {
        Map<String, Object> map = new HashMap<>();
        map.put("rate", 0);
        List<Comment> allList = commentMapper.findAllInfoByForeignId(foreignId);
        List<Comment> rootComments = allList.stream().filter(item ->
                item.getPid() == null
        ).collect(Collectors.toList());
        rootComments.stream().map(Comment::getRate).reduce((a, b) -> a + b).ifPresent(result -> {
            map.put("rate", result / rootComments.size());
        });
        for (Comment comment : rootComments) {
            comment.setChildren(allList.stream().filter(item -> item.getPid() == comment.getUserId()).collect(Collectors.toList()));
        }
        map.put("list", rootComments);
        return map;
    }
}